const userModel = require('../model/userModel.js')
const check = require('../utils/checkUserInfo.js')
const { UserFriendList } =require('../model/socketModel.js')
const {
	sign
} = require('jsonwebtoken');
const {
	secret
} = require('../../config.js')
const {
	setToken
} = require('../utils/tokenAuth.js')
const {
	UserRegisterCheckName,
	UserInfoUpdate,
	UserListSearch
} = require('../model/userModel.js')
module.exports = {
	Login: async ctx => {
		const {
			user_name,
			user_pwd
		} = ctx.request.body
		if (!check.checkUserInfo(ctx, user_name, user_pwd)) {
			return
		}
		let findOut = await userModel.UserLogin(user_name, user_pwd)
		if (findOut.length === 1) {
			const user = findOut[0]
			const token = await setToken(user)
			ctx.body = {
				code: 200,
				data: {
					token
				},
				msg: '成功'
			}
			return
		}
		ctx.body = {
			code: 201,
			msg: '用户名或密码不正确'
		}
	},
	Register: async ctx => {
		const {
			user_name,
			user_pwd
		} = ctx.request.body
		if (!check.checkUserInfo(ctx, user_name, user_pwd)) {
			return
		}
		if (!check.checkRegisterInfo(ctx, user_name)) {
			return
		}
		// 校验是否已有用户名
		const findNameOut = await UserRegisterCheckName(user_name)
		if (findNameOut.length > 0) {
			ctx.body = {
				code: 201,
				msg: "该用户名已被注册，请更换用户名"
			}
			return
		}
		// 插入数据库
		let setOut = await userModel.UserRegister(user_name, user_pwd)
		if (setOut) {
			ctx.body = {
				code: 200,
				data: {
					user_name
				},
				msg: '注册成功'
			}
			return
		}
		ctx.body = {
			code: 201,
			msg: '注册失败,请联系管理员'
		}
	},
	UserInfo: async ctx => {
		let {
			user_id
		} = ctx.state.data
		let userInfo = await userModel.UserInfo(user_id)
		if (userInfo.length === 1) {
			ctx.body = {
				code: 200,
				data: userInfo[0]
			}
		} else {
			ctx.body = {
				code: 201,
				msg: '未找到此用户',
				data: null
			}
		}
	},
	UserInfoEdit:async ctx =>{
		const { user_id } = ctx.state.data
		const editInfo = ctx.request.body
		let userInfo = await UserInfoUpdate(user_id,editInfo)
		if(userInfo){
			ctx.body = {
				code:200,
				msg:'修改成功'
			}
		}else {
			ctx.body = {
				code: 201,
				msg: '修改用户信息失败',
				data: null
			}
		}
	},
	UserListSearch:async ctx=>{
		const {user_nickname} = ctx.query
		let { user_id } = ctx.state.data
		let userList = await UserListSearch(user_id,user_nickname)
		let friendsList = await UserFriendList({user_id,no_group:true})
		userList.forEach(item=>{
			if(friendsList.find(friends=>{return friends.user_id == item.user_id})){
				item.isFriend = true
			}else{
				item.isFriend = false
			}
		})
		ctx.body = {
			code:200,
			data:userList
		}
	}
}
